package com.kungfu.controller;

import com.kungfu.config.Constant;
import com.kungfu.dao.TestMapper;
import com.kungfu.entity.Test;
import com.kungfu.entity.response.BaseResponse;
import com.kungfu.service.MxService;
import com.kungfu.utils.ResultCodeEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

@RestController
public class ExtendController extends BaseController {
    @Autowired
    private MxService mxService;

    @Autowired
    private TestMapper testMapper;

    @PostMapping("/test")
    public ResponseEntity<String> test(@RequestBody Test name) {
        return ResponseEntity.ok("hello" + name.getName());
    }

    @GetMapping("/updateBaseData")
    public ResponseEntity<String> reloadData() {
        BaseResponse response = new BaseResponse();
        int result = mxService.queryAllMx();
        if (result > 0) {
            response.setResult(ResultCodeEnum.SUCCESS);
        } else {
            response.setResult(ResultCodeEnum.SERVER_INTERNAL_ERROR);
        }
        return ResponseEntity.ok(response.toString());
    }

    @PostMapping("/getUpdate")
    private ResponseEntity<byte[]> downloadFile() throws IOException {
        String filePath = Constant.FILL_PATH + "/" + "gfjsData.jar";
        File file = new File(filePath);
        byte[] buffer = null;
        FileInputStream fis = new FileInputStream(file);
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        byte[] b = new byte[1024];
        int n;
        while ((n = fis.read(b)) != -1) {
            bos.write(b, 0, n);
        }
        fis.close();
        bos.close();
        buffer = bos.toByteArray();
        return ResponseEntity.ok()
                .body(buffer);
    }
}
